<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<link rel="stylesheet" href="css/bootstrap-3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="css/register.css" />
<link rel="stylesheet" href="css/listCommon.css" />
<link rel="stylesheet" href="css/evaluation.css" />
<style>
    .modal-backdrop {
        position: inherit;
    }
    #jstree_div::-webkit-scrollbar, #relateListDiv::-webkit-scrollbar{
        width:10px;
        height:10px;
    }
</style>
<jsp:include page="../../../common/nav.jsp"></jsp:include>
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="purchaseOrder">
        <input id="id" name="id" type="hidden" value="${requestScope.purchasingRequisition.id}">
        <div class="formTitle">采购申请单信息</div>
        <div class="trackInfomation">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>标题：</label>
                        <input id="title" name="title" type="text" class="form-control" placeholder="请输入标题" value="${requestScope.purchasingRequisition.title}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span id="">*</span>
                        <label>采购类型：</label>
                        <select id="type" name="type" class="form-control" disabled>
                            <option value="">请选择采购类型</option>
                            <c:forEach items="${requestScope.typeMap}" var="typeMap">
                                <c:if test="${typeMap.key == requestScope.purchasingRequisition.type}">
                                    <option value="${typeMap.key}" selected>${typeMap.value}</option>
                                </c:if>
                                <c:if test="${typeMap.key != requestScope.purchasingRequisition.type}">
                                    <option value="${typeMap.key}">${typeMap.value}</option>
                                </c:if>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>期望交货时间：</label>
                        <input id="scheduledTime" name="scheduledTime" type="date" class="form-control" value="${requestScope.purchasingRequisition.scheduledTime}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <span>*</span>
                        <label>采购原因：</label>
                        <input id="reason" name="reason" type="text" class="form-control" placeholder="请输入采购原因" value="${requestScope.purchasingRequisition.reason}">
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <span>&nbsp;&nbsp;</span>
                        <label class="fuyanText">附言(摘要)：</label>
                        <textarea id="remark" name="remark" class="form-control fuyan" rows="3" placeholder="请输入附言" style="margin-left: 0;height:80px !important;" disabled>${requestScope.purchasingRequisition.remark}</textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="formTitle">采购人信息</div>
        <div class="trackInfomation">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>申请人：</label>
                        <input id="createUserName" type="text" class="form-control" value="${requestScope.purchasingRequisition.createUserName}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>公司代码：</label>
                        <input id="companyCode" name="companyCode" type="text" class="form-control" value="${requestScope.purchasingRequisition.companyCode.concat(' - '.concat(requestScope.purchasingRequisition.companyName))}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>申请部门：</label>
                        <input id="departmentCode" name="departmentCode" type="hidden" value="${requestScope.purchasingRequisition.departmentCode}">
                        <input id="departmentName" name="departmentName" type="text" class="form-control" value="${requestScope.purchasingRequisition.departmentName}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>电子邮箱：</label>
                        <input id="mailbox" type="text" class="form-control" value="${requestScope.purchasingRequisition.mailbox}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>手机号码：</label>
                        <input id="tel" type="text" class="form-control" placeholder="请输入手机号码" value="${requestScope.purchasingRequisition.tel}" disabled>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>固定电话：</label>
                        <input id="landLine" type="text" class="form-control" value="${requestScope.purchasingRequisition.landLine}" disabled>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <label class="fuyanText">收货地址：</label>
                        <textarea id="address" name="address" class="form-control fuyan" rows="3" placeholder="请输入收货地址" style="margin-left: 0;height:80px !important;" disabled>${requestScope.purchasingRequisition.address}</textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="formTitle">
            物资信息
        </div>
        <div class="tableWrap">
            <table class="table table-bordered">
                <thead id="subBody">
                <tr>
                    <th width="5%">序号</th>
                    <th>物料编码</th>
                    <th>品牌</th>
                    <th>物资名称</th>
                    <th>型号</th>
                    <th>类目</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th width="10%">附件</th>
                    <th>状态</th>
                    <th width="20%">附言</th>
                    <th width="10%">操作</th>
                </tr>
                <c:if test="${empty requestScope.purchasingRequisition.subs}">
                    <tr id="nothing">
                        <td colspan="12" style="color: #bbbbbb">无物资信息</td>
                    </tr>
                </c:if>
                <c:if test="${not empty requestScope.purchasingRequisition.subs}">
                    <c:forEach items="${requestScope.purchasingRequisition.subs}" var="sub" varStatus="index">
                        <tr id="${"materialLine".concat(index.count)}">
                            <td id="${"materialNo".concat(index.count)}">${index.count}</td>
                            <td id="${"detailId".concat(index.count)}" style="display: none">${sub.id}</td>
                            <td id="${"materialId".concat(index.count)}" style="display: none">${sub.materialId}</td>
                            <td id="${"materialCode".concat(index.count)}">${sub.materialCode}</td>
                            <td id="${"materialBrand".concat(index.count)}">${sub.materialBrand}</td>
                            <td id="${"materialName".concat(index.count)}">${sub.materialName}</td>
                            <td id="${"materialModel".concat(index.count)}">${sub.materialModel}</td>
                            <td id="${"materialCategory".concat(index.count)}">${sub.materialCategory}</td>
                            <td><input id="${"quantity".concat(index.count)}" type="number" style="border:1px solid #ddd;width:60px;border-radius:4px;" value="${sub.quantity}"></td>
                            <td id="${"materialUnit".concat(index.count)}">${sub.materialUnit}</td>
                            <c:if test="${'' == sub.accessory}">
                                <td id="${"subFilePath".concat(index.count)}" style="display: none"></td>
                                <td id="${"subFileTd".concat(index.count)}"><input id="${"subFile".concat(index.count)}" type="file"></td>
                            </c:if>
                            <c:if test="${'' != sub.accessory}">
                                <td id="${"subFilePath".concat(index.count)}">
                                    <a style="text-decoration: none; color: black" download="${sub.accessoryName}" href="${sub.accessory}">${sub.accessoryName}</a>
                                    <a style="float: right;color:red; cursor: pointer;" onclick="clearSubFile(${index.count})">X</a>
                                </td>
                                <td id="${"subFileTd".concat(index.count)}" style="display: none"><input id="${"subFile".concat(index.count)}" type="file"></td>
                            </c:if>
                            <td id="${"subStatus".concat(index.count)}" style="display: none">${sub.status}</td>
                            <td id="${"subStatusText".concat(index.count)}">${requestScope.subStatusMap[sub.status]}</td>
                            <td><input id="${"subRemark".concat(index.count)}" type="text" style="border:1px solid #ddd;width:100%;border-radius:4px;" value="${sub.remark}"></td>
                            <td id="${"materialOperation".concat(index.count)}" class="attachment">
                                <button id="materialUpload' + subSize + '" type="button" style="margin-left: 3px" onclick="uploadMaterial(${index.count})">上传附件</button>
                                <button id="${"materialDel".concat(index.count)}" type="button" style="margin-left: 3px" onclick="delMaterial(${index.count})">删除</button>
                            </td>
                        </tr>
                    </c:forEach>
                </c:if>
                </thead>
            </table>
        </div>
        <div class="formTitle">
            附件信息
        </div>
        <div class="tableWrap">
            <table class="table table-bordered">
                <thead id="fileBody">
                <tr>
                    <th width="5%">序号</th>
                    <th>附件名称</th>
                </tr>
                <c:if test="${empty requestScope.purchasingRequisition.accessory}">
                    <tr id="fileNothing">
                        <td colspan="2" style="color: #bbbbbb">无附件信息</td>
                    </tr>
                </c:if>
                <c:if test="${not empty requestScope.purchasingRequisition.accessory}">
                    <c:forEach items="${requestScope.purchasingRequisition.fileMap}" var="file" varStatus="index">
                        <tr id="${"fileLine".concat(index.count)}">
                            <td id="${"fileNo".concat(index.count)}">${index.count}</td>
                            <td id="${"fileName".concat(index.count)}">
                                <a style="text-decoration: none; color: black" download="${file.value}" href="${file.key}">${file.value}</a>
                            </td>
                        </tr>
                    </c:forEach>
                </c:if>
                </thead>
            </table>
        </div>
        <div class="trackSubmit">
            <button type="button" onclick="save()">提交</button>
            <button type="button" onclick="window.location.href='web/purchasingAudit/show'">返回</button>
        </div>
    </div>
</div>
<script src="css/bootstrap-3.3.7/js/jquery-2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="css/bootstrap-3.3.7/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
<script>

    var delIds = [];
    var subSize = ${requestScope.purchasingRequisition.id != null} ? "${requestScope.purchasingRequisition.subs.size()}" : 0;
    var fileList = ${requestScope.purchasingRequisition.id != null} && ${not empty requestScope.purchasingRequisition.accessory}
        ? "${requestScope.purchasingRequisition.accessory}".split("FILE_NAME_END")
        : [];

    // 上传物资附件
    function uploadMaterial(index) {
        let files = $('#subFile' + index)[0].files;
        if (files.length > 0) {
            let formData = new FormData();
            for(let i = 0; i < files.length; i ++){
                if (files[i].size > 1048576) {
                    redragonJS.alert("文件过大,无法上传!");
                    return;
                }
                formData.append("accessory", files[i]);
            }
            $.ajax({
                type: 'post',
                url: "web/purchasingRequisition/upload",
                data: formData,
                dataType: "json",
                cache: false,
                processData: false,
                contentType: false,
                async: false,
                success: function (data) {
                    if (data.length > 0) {
                        $("#subFilePath" + index).html(
                            '<a style="text-decoration: none; color: black" download="' + data[0].name + '" href="' + data[0].url + '">' + data[0].name + '</a>' +
                            '<a style="float: right;color:red; cursor: pointer;" onclick="clearSubFile(' + index + ')">X</a>'
                        ).removeAttr("style");
                        $("#subFile" + index).val("");
                        $("#subFileTd" + index).attr("style", "display:none;")
                    } else {
                        redragonJS.alert("上传失败!");
                    }
                }
            });
        }
    }

    // 删除物资附件
    function clearSubFile(index) {
        $("#subFilePath" + index).html("").attr("style", "display:none;");
        $("#subFileTd" + index).removeAttr("style")
    }

    // 删除物资信息
    function delMaterial(index) {
        if (subSize == 1) {
            redragonJS.alert("至少需要保留一条数据!");
            return;
        }
        delIds.push($("#detailId" + index).text());
        $("#materialLine" + index).remove();
        if (index < subSize) {
            for (var i = index + 1; i <= subSize; i ++) {
                let num = i - 1;
                $("#materialLine" + i).attr("id", "materialLine" + num);
                $("#materialNo" + i).text(num).attr("id", "materialNo" + num);
                $("#detailId" + i).attr("id", "detailId" + num);
                $("#materialId" + i).attr("id", "materialId" + num);
                $("#materialCode" + i).attr("id", "materialCode" + num);
                $("#materialBrand" + i).attr("id", "materialBrand" + num);
                $("#materialName" + i).attr("id", "materialName" + num);
                $("#materialModel" + i).attr("id", "materialModel" + num);
                $("#materialCategory" + i).attr("id", "materialCategory" + num);
                $("#quantity" + i).attr("id", "quantity" + num);
                $("#materialUnit" + i).attr("id", "materialUnit" + num);
                $("#subFilePath" + i).attr("id", "subFilePath" + num);
                $("#subFileTd" + i).attr("id", "subFileTd" + num);
                $("#subFile" + i).attr("id", "subFile" + num);
                $("#subStatus" + i).attr("id", "subStatus" + num);
                $("#subStatusText" + i).attr("id", "subStatusText" + num);
                $("#subRemark" + i).attr("id", "subRemark" + num);
                $("#materialOperation" + i).attr("id", "materialOperation" + num);
                $("#materialUpload" + i).attr("id", "materialUpload" + num).attr("onclick", "uploadMaterial(" + num + ")");
                $("#materialDel" + i).attr("id", "materialDel" + num).attr("onclick", "delMaterial(" + num + ")");
            }
        }
        if (-- subSize == 0) {
            $("#subBody").append(
                '<tr id="nothing">' +
                '<td colspan="12" style="color: #bbbbbb">无物资信息</td>' +
                '</tr>'
            );
        }
    }

    // 保存
    function save() {
        for (let i =1; i <= subSize; i ++) {
            let num = $("#quantity" + i).val();
            if (num == "") {
                redragonJS.alert("请输入序号为:" + i + "的物资的数量!");
                return;
            } else if (num <= 0) {
                redragonJS.alert("序号为:" + i + "的物资的数量必须大于0!");
                return;
            } else if (num % 1 != 0) {
                redragonJS.alert("序号为:" + i + "的物资的数量必须为整数!");
                return;
            }
        }
        $.ajax({
            url : "web/purchasingRequisition/save",
            contentType : "application/json",
            dataType : 'json',
            data : JSON.stringify(getSubmitInfo()),
            type:'post',
            async : true,
            success : function(data) {
                if(data.code == 1) {
                    redragonJS.alert("操作成功!");
                    setTimeout(function(){
                        window.location.href='web/purchasingAudit/show'
                    },1000);
                } else {
                    redragonJS.alert(data.msg);
                }
            }
        });
    }

    // 获取提交数据
    function getSubmitInfo() {
        let data = {};
        data.id = $("#id").val();
        data.title = $("#title").val();
        data.type = $("#type").val();
        data.companyCode = "${requestScope.purchasingRequisition.companyCode}";
        data.companyName = "${requestScope.purchasingRequisition.companyName}";
        data.departmentCode = $("#departmentCode").val();
        data.departmentName = $("#departmentName").val();
        data.createUserName = $("#createUserName").val();
        data.tel = $("#tel").val();
        data.landLine = $("#landLine").val();
        data.mailbox = $("#mailbox").val();
        data.scheduledTime = $("#scheduledTime").val();
        data.reason = $("#reason").val();
        data.address = $("#address").val();
        data.accessory = getAccessory();
        data.remark = $("#remark").val();
        data.allowedWithdraw = "0";
        data.ids = delIds;
        let subs = [];
        for(var i = 1; i <= subSize; i ++){
            let sub = {};
            sub.id = $("#detailId" + i).text();
            sub.materialId = $("#materialId" + i).text();
            sub.materialCode = $("#materialCode" + i).text();
            sub.materialBrand = $("#materialBrand" + i).text();
            sub.materialName = $("#materialName" + i).text();
            sub.materialModel = $("#materialModel" + i).text();
            sub.materialCategory = $("#materialCategory" + i).text();
            sub.quantity = $("#quantity" + i).val();
            sub.materialUnit = $("#materialUnit" + i).text();
            sub.accessory = $("#subFilePath" + i + " a:first-child").attr("href");
            sub.remark = $("#subRemark" + i).val();
            subs.push(sub);
        }
        data.subs = subs;
        return data;
    }

    // 获取附件字符串
    function getAccessory() {
        if (fileList.length == 0) {
            return "";
        } else {
            let result = fileList[0];
            for (let i = 1; i < fileList.length; i ++) {
                result += "FILE_NAME_END" + fileList[i];
            }
            return result;
        }
    }
</script>